package com.xusiyan08.repository;

import com.xusiyan08.entity.Message;
import feign.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

@Repository
public interface MessageRepository extends JpaRepository<Message, Long> {
    List<Message> findByReceiverId(Long receiverId);
   // List<Message> findBySenderIdAndReceiverId(Long senderId, Long receiverId);
// 可能需要调整这个查询以获取与 user1 或 user2 的对话，并按时间排序
   List<Message> findBySenderIdAndReceiverId(Long userId1, Long userId2);

    // 添加一个查询来获取与给定用户相关的所有不同用户的 ID
    @Query("SELECT DISTINCT m.senderId FROM Message m WHERE m.receiverId = :userId")
    Set<Long> findDistinctSenderIdsByReceiverId(@Param("userId") Long userId);

    @Query("SELECT DISTINCT m.receiverId FROM Message m WHERE m.senderId = :userId")
    Set<Long> findDistinctReceiverIdsBySenderId(@Param("userId") Long userId);

    List<Message> findByItemIdOrderByCreatedAtAsc(Long itemId);

    @Query("SELECT COUNT(m) FROM Message m WHERE m.receiverId = :sellerId AND m.isRead = FALSE AND m.itemId IS NOT NULL")
    Long countUnreadCommentsBySellerId(@Param("sellerId") Long sellerId);

    @Query("SELECT COUNT(m) FROM Message m WHERE m.itemId = :itemId AND m.receiverId = :receiverId AND m.isRead = FALSE")
    Long countUnreadCommentsByItemIdAndReceiverId(@Param("itemId") Long itemId, @Param("receiverId") Long receiverId);
}